<template>
  <div class="view-flex-plan" v-bind="$attrs">
    <px-scrollbar ref="scrollbarRef" class="inspect-task-detail-content" @scroll="handleScroll">
      <div ref="basicsRef">
        <div class="view-equip-title">基础信息</div>
        <ColumnsTable :columns="INSPECTTASKDETAIL_BASEINFO_COLUMNS_PLAN" :data="detailData" />
      </div>
      <div ref="contentRef" class="view-equip-title">巡检内容</div>
      <ColumnsTable :columns="areaColumns" :data="detailData">
        <template #value="{ scope }">
          <template v-if="scope.prop === 'checkAreaDesc' && detailData.checkAreaDesc">
            <px-tag v-for="(item, index) in detailData.checkAreaDesc.split(',')" :key="index" class="ml-2" type="info">{{ item }}</px-tag>
          </template>
          <template v-if="scope.prop === 'checkType' && detailData.checkType">
            {{ dealCheckTypeName(detailData.checkType) }}
          </template>
        </template>
      </ColumnsTable>
      <div class="view-plan-wrap noborder">
        <div class="view-plan-content">
          <InspectRulesTable :table-data="tableData || []" :tableColumns="tableColumns" :total="0" class="w-[100%]" />
        </div>
      </div>
      <div ref="timeRangeRef" class="view-equip-title">执行周期</div>
      <div class="view-plan-wrap">
        <div class="view-plan-content">
          <div class="view-plan-item">
            <div class="label">执行方式</div>
            <div class="text">{{ ["", "固定时间", "周期时间"][detailData.execType] }}</div>
          </div>
          <div class="view-plan-item">
            <div class="label">开始时间</div>
            <div class="text">{{ detailData.execStartDate }}</div>
          </div>
          <div class="view-plan-item">
            <div class="label">结束时间</div>
            <div class="text">{{ detailData.execEndDate }}</div>
          </div>
        </div>
        <template v-if="detailData.execType == 2">
          <div class="view-plan-content">
            <div class="view-plan-item plus">
              <div class="label">排查周期</div>
              <div v-if="['DAY', 'WEEK', 'MONTH'].includes(detailData.cyclePerUnit)" class="text">
                {{ dealExecTime() }}
                <px-tag v-for="item in weeks" :key="item" class="ml-[6px]" type="info">{{ item }}</px-tag>
                <px-tag v-for="item in days" :key="item" class="ml-[6px]" type="info">{{ item }}</px-tag>
              </div>
              <div v-else class="text">
                {{ dealExecTime() }}
                <px-tag v-for="item in months" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                的
                <px-tag v-for="item in days" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                日
              </div>
            </div>
          </div>
          <div class="view-plan-content">
            <div class="view-plan-item">
              <div class="label">任务执行时间</div>
              <div class="text">
                <px-tag v-for="item in operates" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
              </div>
            </div>
            <div class="view-plan-item">
              <div class="label">执行时长</div>
              <div class="text">{{ `${detailData.execDuration}${unitList[detailData.execDurationUnit]}` }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">宽泛期</div>
              <div class="text">{{ `${detailData.extendDuration}${unitList[detailData.extendDurationUnit]}` }}</div>
            </div>
          </div>
          <div class="view-plan-content">
            <div class="view-plan-item plus">
              <div class="label">任务生成并提醒时间</div>
              <div class="text">{{ taskList[detailData.taskCreateTime] }}</div>
            </div>
          </div>
        </template>
      </div>

      <div ref="eqpRef" class="view-equip-title">巡检设备</div>
      <div class="view-plan-wrap noborder">
        <div class="view-plan-content">
          <InspectRulesTable :table-data="tableEqiupSelected" :tableColumns="tableEqiupColums" :total="0" class="w-[100%]" />
        </div>
      </div>
    </px-scrollbar>
    <WidgetRouter :router-list="routerList" :scrollbar-ref="scrollbarRef" :scroll-top="scrollTop" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, watchEffect } from "vue";
import ColumnsTable from "../../components/ColumnsTable.vue";
import { WidgetRouter } from "../../components/index";
import { INSPECTTASKDETAIL_BASEINFO_COLUMNS_PLAN } from "../config";
import InspectRulesTable from "./InspectRulesTable.vue";

import { getByPlanNo } from "@/api/erc/inspectTask";
import { cloneDeep, debounce } from "@pureadmin/utils";
import { TableItem } from "../../types";
const props = defineProps(["planNo", "taskNo"]);
const tableEqiupColums = ref<TableItem[]>([
  { prop: "index", minWidth: "55", fixed: "left" },
  { prop: "eqpId", label: "设备编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "eqpName", label: "设备名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "eqpSys", label: "设备系统", minWidth: "160", showOverflowTooltip: true },
  { prop: "typeName", label: "设备类型", minWidth: "160", showOverflowTooltip: true },
  { prop: "specification", label: "设备型号", minWidth: "160", showOverflowTooltip: true },
  { prop: "positionName", label: "位置信息", minWidth: "160", showOverflowTooltip: true }
]);
const state = reactive<any>({
  tableColumns: [
    { prop: "expend", minWidth: "55", fixed: "left" },
    { prop: "checkRuleNo", label: "规则编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
    { prop: "checkRuleName", label: "巡检规则名称", minWidth: "160", showOverflowTooltip: true },
    { prop: "facName", label: "地块", minWidth: "160", showOverflowTooltip: true },
    { prop: "eqpTypeName", label: "设备类型", minWidth: "160", showOverflowTooltip: true },
    { prop: "ruleTypeName", label: "规则类型", minWidth: "160", showOverflowTooltip: true }
    // { prop: "recommendDay", label: "建议工作天数", minWidth: "160", showOverflowTooltip: true }
  ],
  areaColumns: [
    [
      { label: "巡检区域", value: "checkAreaDesc", col: "max" },
      { label: "巡检内容", value: "checkType", col: "max" }
    ]
  ]
});
const { tableColumns, areaColumns } = toRefs(state);
const checkAreaDescArr = ref([]);

const detailDataTmpl = {
  planNo: "",
  planName: "",
  planStatus: 0, //1-草稿,2-未开始,3-进行中,4-已完成
  execType: 1, //执行方式 1-固定时间,2-周期时间
  execStartDate: "",
  execEndDate: "",
  execDuration: 0,
  execDurationUnit: "HOUR",
  extendDuration: 0,
  extendDurationUnit: "HOUR",
  factoryAreaCode: "",
  checkArea: "",
  checkGroupCode: "",
  cyclePerNum: 0,
  cyclePerUnit: "DAY",
  cycleValue: "",
  cycleTime: "",
  taskCreateTime: "",
  description: "",
  eqpRelationList: [],
  checkRuleNos: []
};
const detailData = ref(cloneDeep(detailDataTmpl));
const weeksMap = {
  MONDAY: "星期一",
  TUESDAY: "星期二",
  WEDNESDAY: "星期三",
  THURSDAY: "星期四",
  FRIDAY: "星期五",
  SATURDAY: "星期六",
  SUNDAY: "星期日"
};
const monthArr = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);
const operateTimeArr = Array.from({ length: 24 }, (_, i) => (i < 10 ? `0${i}:00` : `${i}:00`));
const unitList = {
  DAY: "日",
  HOUR: "小时"
};
const taskList = ["", "准点生成", "提前10分钟", "提前30分钟", "提前1小时", "提前1天"];
const weeks = ref([]);
const days = ref([]);
const months = ref([]);
const operates = ref([]);
// 巡检规则table
const tableData = ref([]);
//选择设备table
const tableEqiupSelected = ref([]);
//右侧滚动导航
const scrollbarRef = ref(null);
const routerList = ref([]);
const scrollTop = ref();
//表格ref
const basicsRef = ref(null);
const contentRef = ref(null);
const timeRangeRef = ref(null);
const eqpRef = ref(null);
const checkTypeArr = { equipment: "设备巡检", environment: "环境巡检" };
const dealCheckTypeName = checkType => {
  if (!checkType || !checkType.length) return "";
  return checkType.reduce((acc, cur) => {
    if (!acc) return checkTypeArr[cur];
    return acc + "," + checkTypeArr[cur];
  }, "");
};
function resetTime() {
  weeks.value = [];
  days.value = [];
  months.value = [];
}
function dealExecTime() {
  resetTime();
  if (detailData.value.cyclePerUnit === "YEAR") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}年的`;
    }
  } else if (detailData.value.cyclePerUnit === "HALF_YEAR") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}个半年的`;
    }
  } else if (detailData.value.cyclePerUnit === "QUARTER") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}季度的`;
    }
  } else if (detailData.value.cyclePerUnit === "DAY") {
    if (detailData.value.cyclePerNum) {
      return `每${detailData.value.cyclePerNum}天`;
    }
  } else if (detailData.value.cyclePerUnit === "WEEK") {
    if (detailData.value.cyclePerNum) {
      if (detailData.value.cycleValue) {
        let arr = detailData.value.cycleValue.split(",");
        // arr.forEach(item => {
        //   weeks.value.push(weeksMap[item]);
        // });
        Object.keys(weeksMap).forEach(item => {
          if (arr.includes(item)) {
            weeks.value.push(weeksMap[item]);
          }
        });
      }
      return `每${detailData.value.cyclePerNum}周的`;
    }
  } else if (detailData.value.cyclePerUnit === "MONTH") {
    if (detailData.value.cyclePerNum) {
      if (detailData.value.cycleValue) {
        let arr = detailData.value.cycleValue.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      return `每${detailData.value.cyclePerNum}月的`;
    }
  }
}
//右侧滚动导航相关函数
const handleScroll = debounce(({ scrollTop: curScrollTop }) => {
  scrollTop.value = curScrollTop;
}, 200);
const scrollInit = () => {
  let routerName = "基本信息,巡检内容,执行周期,巡检设备";
  let routerRefs = [basicsRef, contentRef, timeRangeRef, eqpRef];
  routerList.value = routerName.split(",").map((item, index) => {
    return { ref: routerRefs[index], name: item };
  });
};
// 后端同学表示任务详情计划相关字段不全，需从计划接口获取
watchEffect(async () => {
  if (!props.planNo || !props.taskNo) {
    return;
  }
  let detail: { [key in string] } = await getByPlanNo({
    planNo: props.planNo,
    taskNo: props.taskNo
  });
  detail.execType = String(detail.execType);
  const { checkRuleList, eqpList, checkAreaDesc, cycleTime } = detail as any;
  // queryTable();
  tableData.value = checkRuleList?.length > 0 ? checkRuleList : [];
  tableEqiupSelected.value = eqpList?.length > 0 ? eqpList : [];
  detailData.value = detail;
  if (checkAreaDesc) {
    checkAreaDescArr.value = checkAreaDesc.split(",");
  }
  if (cycleTime) {
    const arr = cycleTime.split(",").sort((a, b) => a - b);
    operates.value = arr.reduce((pre, cur) => {
      return [...pre, operateTimeArr[cur]];
    }, []);
  }
});
watchEffect(() => {
  scrollInit();
});
</script>

<style lang="scss" scoped>
.view-flex-plan {
  position: relative;
  display: flex;
  height: calc(100vh - 260px);
  .view-plan-wrap {
    margin-bottom: 32px;
    border-top: 1px solid #dfdfdf;
    border-left: 1px solid #dfdfdf;

    &.noborder {
      border-style: none;
    }

    .view-plan-content {
      display: flex;
      color: #000;

      .view-plan-item {
        display: flex;
        width: 33.3333%;
        min-height: 40px;
        line-height: 22px;
        border-right: 1px solid #dfdfdf;
        border-bottom: 1px solid #dfdfdf;

        .label {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          flex-shrink: 0;
          width: 120px;
          padding: 8px 12px;
          font-size: 14px;
          font-weight: bold;
          background: #e7eefb;
          border-right: 1px solid #dfdfdf;
        }

        .text {
          display: flex;
          flex: 1;
          align-items: center;
          flex-wrap: wrap;
          padding: 0 12px;
          padding-top: 8px;
          padding-bottom: 8px;
          font-size: 14px;
          line-height: 18px;
          word-break: break-all;

          .tag {
            height: 22px;
            padding: 0 8px;
            font-size: 12px;
            line-height: 22px;
            color: rgb(0 0 0 / 80%);
            text-align: center;
            border-radius: 4px;
          }
        }

        &.large {
          width: 66.6666%;
        }

        &.plus {
          width: 100%;
        }
      }
    }

    &.view-plan-wrap-second {
      margin-bottom: 12px;
      border-top: 0;

      .view-plan-content {
        justify-content: space-between;

        .view-plan-item {
          border-top: 1px solid #dfdfdf;
        }

        .view-plan-btn {
          display: flex;
          align-items: center;
          height: 40px;
          margin-left: 16px;
          line-height: 22px;
        }
      }
    }
  }
}
.view-equip-title {
  height: 22px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  line-height: 22px;
  color: rgb(0 0 0 / 80%);
}
.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-left: 20px;
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;

      .circle {
        width: 8px;
        height: 8px;
        margin-left: 8px;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
  }
}
.view-mb20 {
  margin-bottom: 20px;
}
:deep(.inner-tabel) {
  width: 100%;
}
:deep(.inspect-task-detail-content) {
  min-width: 500px;
  width: 100%;
}
</style>
